package me.work.pay.jsyl.mvp.ui.activity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.VideoView;

import com.blankj.utilcode.util.ObjectUtils;
import com.blankj.utilcode.util.SPUtils;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.danikula.videocache.HttpProxyCacheServer;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.squareup.picasso.Picasso;
import com.youth.banner.Banner;
import com.youth.banner.loader.ImageLoader;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import me.work.pay.jsyl.R;
import me.work.pay.jsyl.app.Constants;
import me.work.pay.jsyl.app.utils.QRCodeUtil;
import me.work.pay.jsyl.app.utils.RxUtil;
import me.work.pay.jsyl.di.component.DaggerMainLandComponent;
import me.work.pay.jsyl.mvp.contract.MainLandContract;
import me.work.pay.jsyl.mvp.model.AppModel;
import me.work.pay.jsyl.mvp.model.entity.GuanGaoData;
import me.work.pay.jsyl.mvp.model.entity.LauncherData;
import me.work.pay.jsyl.mvp.model.entity.SnData;
import me.work.pay.jsyl.mvp.presenter.MainLandPresenter;

import static com.jess.arms.utils.Preconditions.checkNotNull;
import static me.work.pay.jsyl.app.utils.RxUtil.getProxy;


/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 11/04/2020 22:36
 * <a href="mailto:jess.yan.effort@gmail.com">Contact me</a>
 * <a href="https://github.com/JessYanCoding">Follow me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms">Star me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms/wiki">See me</a>
 * <a href="https://github.com/JessYanCoding/MVPArmsTemplate">模版请保持更新</a>
 * ================================================
 */
public class MainLandActivity extends BaseActivity<MainLandPresenter> implements MainLandContract.View {

    @BindView(R.id.banner)
    Banner mBanner;
    @BindView(R.id.video)
    VideoView mVideo;
    @BindView(R.id.tv1)
    TextView mTv1;
    @BindView(R.id.tv2)
    TextView mTv2;
    @BindView(R.id.iv)
    ImageView mIv;
    @BindView(R.id.iv2)
    ImageView mIv2;
    @BindView(R.id.rl)
    RelativeLayout mRl;
    @BindView(R.id.iv_wx)
    ImageView mIvWx;
    @BindView(R.id.rl2)
    RelativeLayout mRl2;
    private LauncherData launcherData;

    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        DaggerMainLandComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .view(this)
                .build()
                .inject(this);
    }

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        return R.layout.activity_main_land; //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        connectivityManager = (ConnectivityManager) getApplication().getSystemService(Context.CONNECTIVITY_SERVICE);
        launcherData = AppModel.getInstance().getLauncherData();
        if (ObjectUtils.isEmpty(launcherData)) {
            finish();
        }
        if (ObjectUtils.isNotEmpty(launcherData.aerf_sn)) {
            mRl.setVisibility(View.GONE);
            mRl2.setVisibility(View.VISIBLE);
        }
        init_imgs();
        init_qrcode();
        init_video();
    }

    String urls[] = {};
    int now_index = 0;
    private int play_num = 0;//广告播放的次数
    ConnectivityManager connectivityManager;
    private static final int MY_PERMISSIONS_WRITE_EXTERNAL_STORAGE = 1;

    private void init_video() {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                        MY_PERMISSIONS_WRITE_EXTERNAL_STORAGE);
            } else {
                Log.i("aaa", "权限已申请");
                if (urls.length > 0) {
                    initVideo(urls[0]);
                } else {
                    initVideo("");
                }
            }
        }


        mVideo.setOnCompletionListener(mp -> {
            Log.i("aaaapath", urls.length + "");
            if (now_index < urls.length - 1) {
                now_index++;
            } else {
                now_index = 0;
            }
            NetworkInfo info = connectivityManager.getActiveNetworkInfo();
            Log.i("aaaapath", (info == null) + "");
            if (info == null || now_index == 0) {
                initVideo("");
            } else {
                initVideo(urls[now_index]);
            }
            play_num++;
        });

    }

    private void initVideo(String url) {
        HttpProxyCacheServer proxy = getProxy(getApplicationContext());
        //1.我们会将原始url注册进去
        // proxy.registerCacheListener(, bean.getVideo_url());
        //2.我们播放视频的时候会调用以下代码生成proxyUrl
        String proxyUrl = proxy.getProxyUrl(url);
        if (proxy.isCached(url)) {
            Log.i("aaaa", "已缓存");
        } else {
            Log.i("aaaa", "未缓存");
        }
        Log.i("aaaapath1", proxyUrl);
        if (proxyUrl.contains("127.0.0.1")) {
            proxyUrl = "android.resource://me.work.pay.jsyl/" + R.raw.video3;
            mVideo.setVideoURI(Uri.parse(proxyUrl));
        } else {
            mVideo.setVideoPath(proxyUrl);
        }
        mVideo.start();
        mVideo.findFocus();
    }

    private void init_qrcode() {
        SnData aerf_sn = launcherData.aerf_sn;
        if (ObjectUtils.isNotEmpty(aerf_sn) && ObjectUtils.isNotEmpty(aerf_sn.getShort_key_url())) {

            int width = RxUtil.getAutoHeight(getApplicationContext(), 160);
            Bitmap bitmap = QRCodeUtil.createQRCodeBitmap(aerf_sn.getShort_key_url(), width, width);
            mIv.setImageBitmap(bitmap);
            mIv2.setImageBitmap(bitmap);
        }
    }

    private void init_imgs() {
        RequestOptions options = new RequestOptions()
                .centerCrop()
                .diskCacheStrategy(DiskCacheStrategy.ALL);    //缓存所有版本
        mBanner.setImageLoader(new ImageLoader() {
            @Override
            public void displayImage(Context context, Object path, ImageView imageView) {
                imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
//                Glide.with(context).load(path).apply(options).into(imageView);
                Picasso.get()
                        .load(path.toString())
                        .into(imageView);
            }
        });

        List<String> images = new ArrayList<>();
        if (ObjectUtils.isNotEmpty(launcherData)) {
            for (GuanGaoData DownBean : launcherData.aerf_adver_down) {
                images.add(DownBean.getUrl());
            }
        }
        mBanner.setImages(images);
        mBanner.start();
        mBanner.setDelayTime(1500);//设置轮播时间
    }


    Handler handler = new Handler();

    private void init_page() {
        SPUtils.getInstance().put(Constants.sp_page_value, "1");
    }

    @Override
    protected void onResume() {
        super.onResume();
        String page = SPUtils.getInstance().getString(Constants.sp_page_value);
        int time = 0;
        if (("5").equals(page)) {
            time = 2000;
        }
        handler.postDelayed(() -> {
            init_page();
//            mPresenter.getGroup();
        }, time);//3秒后执行Runnable中的run方法
        if (mVideo != null) {
            mVideo.resume();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mVideo != null) {
            mVideo.pause();
        }
//        BLEManager.getDefault().unregisterReceiver();
    }


    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.snackbarText(message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        finish();
    }
}
